'use strict';

/**
 * @ngdoc directive
 * @name jgappApp.directive:dateDirective
 * @description
 * # dateDirective
 */
angular.module('jgappApp')
    .directive('dateDirective', ["$filter", function($filter) {
        return {
            require: 'ngModel',
            restrict: 'AE',
            link: function(scope, element, attrs, ngModelController) {
                var type;
                var currYear = new Date().getFullYear();
                type = attrs.datetype || "date"
                var opt = {};
                opt.default = {
                    display: 'bottom', //显示方式 
                    mode: 'scroller', //日期选择模式
                    lang: 'zh',
                    dateFormat: "yy-mm-dd"
                };
                if (type == "date") {
                    opt.default.minDate = new Date(new Date().setFullYear(currYear - 5));
                    opt.default.maxDate = new Date(new Date().setFullYear(currYear + 5));
                    $(element[0]).mobiscroll(opt.default).date(opt.default);
                } else if (type == "datetime") {
                    opt.default.timeFormat="hh:ii:ss"
                    opt.default.minDate = new Date(new Date().setFullYear(currYear - 5));
                    opt.default.maxDate = new Date(new Date().setFullYear(currYear + 5));
                    $(element[0]).mobiscroll(opt.default).datetime(opt.default);
                } else if (type == "time") {
                    $(element[0]).mobiscroll(opt.default).time(opt.default);
                }
                ngModelController.$formatters.push(function(data) {
                    //convert data from model format to view format
                    var date;
                    if (type == "datetime") {
                        date = $filter("dateFmt")(data, "yyyy-MM-dd hh:mm:ss")
                    } else if (type == "time") {
                        // date = $filter("dateFmt")(data, "hh:mm")
                        date = data
                    } else {
                        date = $filter("dateFmt")(data)
                    }
                    return date //converted
                });
            }
        };
    }]);
